package com.angel.web.health;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.angel.core.Constants;
import com.angel.core.util.FastDFSClient;
import com.angel.core.util.FileUtils;
import com.angel.core.util.JsonUtil;
import com.angel.core.util.MatcherUtil;
import com.angel.core.util.PDFUtils;
import com.angel.core.util.PropertyConfUtil;
import com.angel.health.BuzAssessment;
import com.angel.health.BuzCustomer;
import com.angel.health.BuzExaminationParsingWithBLOBs;
import com.angel.health.BuzFactors;
import com.angel.health.BuzMedicalContent;
import com.angel.healthReport.HeathReport;
import com.angel.provider.health.BuzAssessmentProvider;
import com.angel.provider.health.BuzCustomerProvider;
import com.angel.provider.health.BuzExaminationParsingProvider;
import com.angel.provider.health.BuzFactorsProvider;
import com.angel.provider.health.BuzMedicalContentProvider;
import com.angel.provider.health.BuzRiskFactorsProvider;
import com.angel.provider.health.BuzSurveyProvider;
import com.github.pagehelper.StringUtil;

/**
 * @author 作者姓名 cheng
 * @version 创建时间：2016年10月1日 下午7:31:41 类说明
 */
@Controller
@RequestMapping("app/healthReport")
public class BuzHealthReportController {

	@Autowired
	private BuzExaminationParsingProvider bwpProvider;

	@Autowired
	private BuzRiskFactorsProvider brfProvider;

	@Autowired
	private BuzMedicalContentProvider bmcProvider;

	@Autowired
	private BuzFactorsProvider bfProvider;

	@Autowired
	private BuzSurveyProvider buzSurveyProvider;

	@Autowired
	private BuzCustomerProvider bcProvider;
	
	@Autowired
	private BuzAssessmentProvider baProvider;

	@ResponseBody
	@RequestMapping("generate")
	public String generate(HttpServletRequest request,String customerId) {
		String file = "/health.html";
		String path = request.getRealPath("");
		path = path.replaceAll("\\\\", "/");
		String html = FileUtils.readFileByLines(path + file);
		BuzAssessment ba = new BuzAssessment();
		ba.setCustomerId(Integer.parseInt(customerId));
		List<Map<String, Object>> findAll = baProvider.findAll(ba);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		String id = "";
		if(findAll.size() == 0){
			return JsonUtil.toJson("");
		}else{
			id = findAll.get(0).get("id").toString();
		}
		String assessmentCode =  sdf.format(date).replace("年", "").replace("月", "").replace("日", "")+"000000";
		assessmentCode = assessmentCode.substring(0,assessmentCode.length() - id.length()) + id;
		

		BuzCustomer bc = new BuzCustomer();
		bc.setId(Integer.parseInt(customerId));
		List<Map<String, Object>> customer = bcProvider.findCustomerList(bc);
		html = html.replace("【customerName】", customer.get(0).get("name") == null?"":customer.get(0).get("name").toString());
		html = html.replace("【customerCompany】", customer.get(0).get("companyName") == null?"":customer.get(0).get("companyName").toString());
		
		html = html.replace("【assessmentTime】", sdf.format(date));

		// 问卷调查
		Map<String, String> buzSurvey = buzSurveyProvider.PDFByCustomerId(customerId);
		Map<String, String> wjMap = HeathReport.getWj(buzSurvey);

		html = html.replace("【smoking】", StringUtil.isEmpty(wjMap.get("smoking")) ? "暂无信息" : wjMap.get("smoking"));
		html = html.replace("【drinking】", StringUtil.isEmpty(wjMap.get("drinking")) ? "暂无信息" : wjMap.get("drinking"));
		html = html.replace("【customerSex】", wjMap.get("customerSex"));
		String customerAge = wjMap.get("customerAge");
		if(MatcherUtil.isShu(customerAge)){
			html = html.replace("【customerAge】", Integer.parseInt(customerAge) > 200?"":customerAge);
		}else{
			html = html.replace("【customerAge】", "");
		}
		
		html = html.replace("【exercise】", StringUtil.isEmpty(wjMap.get("exercise"))?"暂无信息":wjMap.get("exercise"));//运动
		html = html.replace("【dh】", StringUtil.isEmpty(wjMap.get("dh"))?"暂无信息":wjMap.get("dh"));//饮食

		String customerSex = wjMap.get("customerSex").trim();
		if (StringUtil.isEmpty(customerSex)) {
			customerSex = "1".equals(customer.get(0).get("sex").toString()) ? "男" : "女";
		}

		// 体检报告解析数据
		BuzExaminationParsingWithBLOBs bxp = new BuzExaminationParsingWithBLOBs();
		bxp.setCustomerId(Integer.parseInt(customerId));
		List<BuzExaminationParsingWithBLOBs> bwpList = bwpProvider.findParsingAll(bxp);

		// 体检指标
		List<BuzMedicalContent> contentList = bmcProvider.findContentAll(null);
		Map<String, BuzMedicalContent> map = HeathReport.medicalContent(contentList);

		// 风险评估参数部分
		List<Map<String, Object>> riskFactorsList = brfProvider.findRiskFactors(null);

		// 危险因素分数
		List<BuzFactors> farctorsList = bfProvider.findAll(null);
		int sex = 1;
		if ("男".equals(customerSex)) {
			sex = 1;
		} else if ("女".equals(customerSex)) {
			sex = 2;
		} else {
			sex = 0;
		}

		// 风险评估得分
		int wjResult = 0;

		if (bwpList.size() > 0) {
			bxp = bwpList.get(0);
			Map<String, String> generateReport = HeathReport.generateReport(bxp.getMedical(),
					sdf.format(bxp.getMedicalTime()), map, sex);

			String medical = generateReport.get("medical");
			Map<String,String> healthMap = HeathReport.health(bxp.getMedical(),wjMap,map,sex);
			html = html.replace("【importantProblem】", healthMap.get("importantProblem"));
			html = html.replace("【secondaryProblem】", healthMap.get("secondaryProblem"));
			html = html.replace("【generalProblem】", healthMap.get("generalProblem"));
//			String importantProblem = generateReport.get("importantIndicator");
//			html = html.replace("【importantIndicator】", importantIndicator);// 阳性发现部分
//			html = html.replace("【pastMedicalHistory】", StringUtil.isEmpty(wjMap.get("pastMedicalHistory")) ? "暂无信息" :wjMap.get("pastMedicalHistory"));//既往史
//			html = html.replace("【familyHistory】", StringUtil.isEmpty(wjMap.get("familyHistory")) ? "暂无信息" :wjMap.get("familyHistory"));//家族史
			html = html.replace("【medicalResults】", medical);// 填充体检报告部分
			String bmi = generateReport.get("bmi");// 体重指数
			String des = HeathReport.getDes(Double.parseDouble(bmi));
			html = html.replace("【weightIndex】", des);
			html = html.replace("【weightIndexNum】", bmi);

			String zjdp = "";
			for (int type = 0; type < 5; type++) {// 0重要指标1.高血压2.脑卒中3.糖尿病4乳腺癌
				if (type == 4 && sex == 1) {
					// 男性乳腺癌没有数据
					html = html.replace("【rxaRiskFactors】", "");// 填充乳腺癌主要参数部分
					html = html.replace("【rxaResult】", "暂无评估");// 填充乳腺癌危险评估结果部分
					html = html.replace("【rxaResultImg】", "0");// 填充乳腺癌危险评估图片等级
					html = html.replace("NO.5", "NO.4");
					html = html.replace("NO.6", "NO.5");
					continue;
				}
				Map<String, String> rfMap = HeathReport.generateRiskFactors(riskFactorsList, type, bxp.getMedical(),
						wjMap, sex);

				String riskFactors = rfMap.get("html");
				rfMap.remove("html");

				// 体检报告中风险评估得分
				String result = "";
				if (type == 4) {
					riskFactors = HeathReport.generateRiskFactorsRXA(riskFactors);
					result = HeathReport.getResultForRXA(rfMap, wjResult);
					html = html.replace("【rxaRiskFactors】", riskFactors);// 填充重要指标主要参数部分
					html = html.replace("【rxaResult】", result.split(":")[0]);// 填充高血压危险评估结果部分
					html = html.replace("【rxaResultImg】", result.split(":")[1]);// 填充高血压危险评估图片等级
					if(Integer.parseInt(result.split(":")[1]) >=3){
						zjdp += "乳腺癌、";
					}
					continue;
				}
				result = HeathReport.getResult(rfMap, farctorsList, type, sex, wjResult);
				if (type == 0) {
					html = html.replace("【zyzbRiskFactors】", riskFactors);// 填充重要指标主要参数部分
				} else if (type == 1) {
					html = html.replace("【gxyRiskFactors】", riskFactors);// 填充高血压主要参数部分
					html = html.replace("【gxyResult】", result.split(":")[0]);// 填充高血压危险评估结果部分
					html = html.replace("【gxyResultImg】", result.split(":")[1]);// 填充高血压危险评估图片等级
					if(Integer.parseInt(result.split(":")[1]) >=3){
						zjdp += "高血压、";
					}
				} else if (type == 2) {
					html = html.replace("【nczRiskFactors】", riskFactors);// 填充主要参数部分
					html = html.replace("【nczResult】", result.split(":")[0]);// 填充脑卒中危险评估结果部分
					html = html.replace("【nczResultImg】", result.split(":")[1]);// 填充脑卒中危险评估图片等级
					if(Integer.parseInt(result.split(":")[1]) >=3){
						zjdp += "脑卒中、";
					}
				} else if (type == 3) {
					html = html.replace("【tnbRiskFactors】", riskFactors);// 填充糖尿病主要参数部分
					html = html.replace("【tnbResult】", result.split(":")[0]);// 填充糖尿病危险评估结果部分
					html = html.replace("【tnbResultImg】", result.split(":")[1]);// 填充糖尿病危险评估图片等级
					if(Integer.parseInt(result.split(":")[1]) >=3){
						zjdp += "糖尿病、";
					}
				} else {

				}
			}
			if(!"".equals(zjdp)){
				html = html.replace("【zjdp】", zjdp.substring(0,zjdp.length() -1 ));
			}

			html = html.replace("【assessmentCode】", assessmentCode);
			UUID uid = UUID.randomUUID();
			PDFUtils.generatePdf(html, path, uid.toString(),request);
			
			
			FastDFSClient client;
			try {
				//生成成功后修改状态
				String fasedfs_url = PropertyConfUtil.getContextProperty(Constants.FASTDFS_UTL);
				client = new FastDFSClient();
				String pdfPath = client.uploadFile(path+"/pdf/"+uid+".pdf");
				System.err.println(pdfPath);
				ba.setAssessmentName(customer.get(0).get("name")+"健康报告");
				ba.setAssessmentTime(date);
				ba.setAssessmentUrl(fasedfs_url+pdfPath);
				int up = baProvider.updateByCustomerId(ba);
				if(up > 0){
					File _file = new File(path+"/pdf/"+uid.toString()+".pdf");
					if(_file.exists()){
						_file.delete();
					}
					return JsonUtil.toJson(fasedfs_url+pdfPath);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				html = "";
			}
		} else {
			html = "";
		}

		return JsonUtil.toJson("");
	}
}
